﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace OCAP_FACAEmail_Api.Controllers
{
    public class SendEMailController : Controller
    {
        // GET: SendEMail
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult SendEMail(string deviceCode,string NextStepName,string resultId,string NextStepNameZh)
        {
            try
            {
                SqlHelper sqlHelper_A = new SqlHelper(2);
                string WebPC_Url = ConfigurationManager.AppSettings["WebPC_Url"];
                string userId_Cmd = $"SELECT [{NextStepName}] FROM [dbo].[OCAP_EMail] Where deviceCode='{deviceCode}'";
                var user_Th = sqlHelper_A.GetData(userId_Cmd);
                if (user_Th.Rows.Count==0 || user_Th.Rows[0][0].ToString()=="")
                {
                    throw new Exception($"设备'{deviceCode}'未在【审批管理】页面维护‘{NextStepNameZh}’信息,发送邮件失败！");
                }
                else
                {
                    string[] userArr = user_Th.Rows[0][0].ToString().Split(',');
                    string users = "";
                    for (var i = 0; i < userArr.Length; i++)
                    {
                        users += i == 0 ? $"'{userArr[i]}'" : $" ,'{userArr[i]}'";
                    }
                    //OCAP_DRI_EMail表是否已维护邮箱
                    string email_Cmd = $"SELECT * FROM [dbo].[OCAP_DRI_EMail] Where 1=1";
                    email_Cmd += users == "" ? $" AND DRI IN ('')" : $" AND DRI IN ({users})";
                    var email_Th = sqlHelper_A.GetData(email_Cmd);
                    if (email_Th.Rows.Count == 0)
                    {
                        throw new Exception($"设备'{deviceCode}'未在【邮件维护】页面维护‘{NextStepNameZh}’的邮件信息,发送邮件失败！");
                    }
                    else
                    {
                        //FACA工程师需要在"历史数据"页面填写FACA,其他人在"FACA审批"页面审批数据
                        string Cur_Url = NextStepNameZh == "FACA工程师" ? $"/ErrorHandle/historyData?deviceCode={deviceCode}" : $"/approve/Approve?resultId={resultId}&deviceCode={deviceCode}";
                        string Title = NextStepNameZh == "FACA工程师" ? $"请填写FACA相关信息" : $"请审批FACA相关信息";
                        string Send_AllDIR = string.Empty;
                        for (int m = 0; m < email_Th.Rows.Count; m++)
                        {
                            Send_AllDIR+=Send_AllDIR == string.Empty ? email_Th.Rows[m]["DRI"].ToString(): $",{email_Th.Rows[m]["DRI"]}";
                        }
                        for (int m = 0; m < email_Th.Rows.Count; m++)
                        {
                            string Email = email_Th.Rows[m]["Email"].ToString();
                            string DRI = email_Th.Rows[m]["DRI"].ToString();

                            JObject job = new JObject();
                            //是否有邮箱
                            job.Add("ToAddress", Email);
                            job.Add("CcAddress", Email);
                            job.Add("SendAddress", "qeworkstation@mektec.com.cn");
                            job.Add("SendName", "OCAP发送");
                            job.Add("Title", Title);
                            job.Add("IsBodyHtml", true);
                            string StepName = string.Empty;
                            string Content =
                                    $"<table align='center' border='1' cellspacing='0'> " +
                                             $"<thead>" +
                                                   $"<tr>" +
                                                       $"<th>设备编号</th>" +
                                                       $"<th>审批人</th>" +
                                                        $"<th>系统地址" +
                                                   $"</tr>" +
                                            $"</thead>" +
                                            $"<tbody align='center' valign='center'>" +
                                                     $"<tr>" +
                                                     $"<td>{deviceCode}</td>" +
                                                     $"<td>{NextStepNameZh}-{Send_AllDIR}</td>" +
                                                      $"<td><a :href='{WebPC_Url}{Cur_Url}'>点击跳转</a></td>" +
                                                 $"</tr>";
                            Content += $"</tbody>" +
                                    $"</table>";
                            job.Add("Content", Content);

                            string JMsx = job.ToString();
                            string SendMailUrl = ConfigurationManager.AppSettings["SendMailUrl"];

                            //发邮件
                            var httpRes = httpPost(SendMailUrl, JMsx);
                            JObject jRes = (JObject)JsonConvert.DeserializeObject(httpRes);
                        }
                    }
                }
                 return Json(new
                {
                    msg = "操作成功",
                    code = 200,
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    msg = ex.Message,
                    code = 500,
                }, JsonRequestBehavior.AllowGet);
            }
        }
        public static string httpPost(string Url, string jsonParas = "")
        {
            string strURL = Url;
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/json";
            //设置参数，并进行URL编码 
            string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);   
            byte[] payload;
            //将Json字符串转化为字节  
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength   
            request.ContentLength = payload.Length;
            //发送请求，获得请求流 
            request.Timeout = 60 * 60 * 1000;
            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                throw new Exception("server connection failed!!!");
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流
                           // String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
            Stream s = response.GetResponseStream();
            //  Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd();
            sRead.Close();
            return postContent;//返回Json数据
        }
    }
}